// 登录相关
import requestInstance from './request';
const http = requestInstance({
  baseURL: 'https://njrsxxzx.cn/njrs/search/api/'
});
/**
 *  完整的登录流程
 */
export function login() {
  return new Promise(async (resolve, reject) => {
    // 获取令牌
    const res = await queryAccessToken();
    if (res.code == 1000) {
      const token = JSON.parse(res.data)
      wx.setStorageSync('accessToken', token.accessToken)
      console.log('accessToken:' + token.accessToken) //打印临时 accessToken 在生产环境复制到开发环境 便于测试 
      wx.setStorageSync('refreshToken', token.refreshToken)
      console.log('refreshToken:' + token.refreshToken) //打印临时 refreshToken 在生产环境复制到开发环境 便于测试 
    } else {
      reject(res)
      return;
    }
    // 获取用户信息
    const res1 = await queryUserInfo();
    if (res1.code == 1000) {
      const userInfo = JSON.parse(res1.data)
      wx.setStorageSync('userInfo', userInfo.data)
      wx.hideLoading();
    } else {
      reject(res1)
      return;
    }
    resolve()
  })
}
// 这是测试获取用户的方法 
testFn()
async function testFn() {
  // 获取用户信息
  const res1 = await queryUserInfo();
  if (res1.code == 1000) {
    const userInfo = JSON.parse(res1.data)
    wx.setStorageSync('userInfo', userInfo.data)
    wx.hideLoading();
  }
}
/**
 * @description 根据省里获取的authCode 获取令牌
 * @param {*} authCode 省里获取的authCode
 */
function queryAccessToken() {
  return http.request({
    url: 'queryAccessToken',
    method: 'POST',
    data: {
      authCode: wx.getStorageSync('authCode')
    }
  })
}
/**
 * @description 获取用户信息
 * @param {*} accessToken 省里获取的令牌
 */
function queryUserInfo() {
  return http.request({
    url: 'queryUserInfo',
    method: 'POST',
    data: {
      accessToken: wx.getStorageSync('accessToken')
    }
  })

}
// 获取用临时token
function queryTicket() {
  return http.request({
    url: 'queryTicket',
    method: 'POST',
    data: {
      openid: '1a481013720f4bd5bc378a448ea016b0',
      thirdChannelType: 'ZJ_WX_MP'
    }
  })
}
// 获取刷新token 当返回报错的时候 就要重新拉起登录页 
export function refreshToken() {
  wx.showLoading({
    title: '刷新登录信息',
  })
  return new Promise(async (resolve, reject) => {
    http.request({
      url: 'refreshToken',
      method: 'POST',
      data: {
        refreshToken: wx.getStorageSync('refreshToken')
      }
    }).then(res => {
      wx.hideLoading()
      if (res.code == 1000) {
        const token = JSON.parse(res.data)
        wx.setStorageSync('accessToken', token.accessToken)
        console.log('刷新accessToken:' + token.accessToken) //打印临时 accessToken 在生产环境复制到开发环境 便于测试 
        wx.setStorageSync('refreshToken', token.refreshToken)
        console.log('刷新refreshToken:' + token.refreshToken) //打印临时 refreshToken 在生产环境复制到开发环境 便于测试 
        wx.showModal({
          showCancel: false,
          content: '登录信息刷新成功！请重新点击您要办理的业务！'
        })
        resolve()
      } else {
        wx.showModal({
          title: '提示',
          content: '登录已过期，是否重新登录？',
          success(res) {
            if (res.confirm) {
              wx.navigateToMiniProgram({
                path: '/pages/humanSociety/appBear',
                appId: 'wx7aa6ad8c15829d96',
                envVersion: 'trial',
                extraData: {
                  appId: '202406040001',
                  forwardUrl: "https://rs.jshrss.jiangsu.gov.cn/mobile/person/login?appId=202406040001&returnUrl=/pages/login/index&channelType=JSHRSS_WXSP&thirdAppId=wxeee1e9fe5686a91e",
                  from: 'miniapp'
                }
              });
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
        reject();
      }
    })
  })

}
// 查询功能方法 获取页面
export function queryTempFunctionCode(functionCode) {
  wx.showLoading({
    title: '加载中',
  })
  return new Promise(async (resolve, reject) => {
    http.request({
      url: 'queryTempFunctionCode',
      method: 'POST',
      data: {
        accessToken: wx.getStorageSync('accessToken'),
        functionCode: functionCode
      }
    }).then(res => {
      wx.hideLoading()
      // 返回正常就走逻辑
      if (res.code == 1000) {
        resolve(res)
      } else if (res.code == 1500) {
        // accessToken无效或已过期 就刷新token
        refreshToken()
      }
    })
  })
}


// 获取ticket 
export function getJsapiTicket(data){
  return http.request({
    url: 'getJsapiTicket',
    method: 'get',
    data: data
  })
}